import markdown
from django.db import models
from django.shortcuts import reverse
from django.contrib.auth.models import User
from django.utils.html import strip_tags


# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=64, verbose_name='分类名')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = verbose_name_plural = '分类'
        db_table = 'category'


class Tag(models.Model):
    name = models.CharField(max_length=64, verbose_name='标签名')

    def __str__(self):
        return self.name

    class Meta:
        # ordering = ['-update_time', '-create_time']
        verbose_name = verbose_name_plural = '标签'
        db_table = 'tag'


class Article(models.Model):
    STATUS = (
        (0, '正常'),
        (1, '草稿'),
        (2, '删除'),
    )
    title = models.CharField(max_length=64, verbose_name='文章标题', help_text='文章标题，尽可能短')
    author = models.ForeignKey(User)
    category = models.ForeignKey(Category, verbose_name='分类')
    status = models.IntegerField(choices=STATUS, verbose_name='状态', default=0)
    tags = models.ManyToManyField(Tag, verbose_name='标签')
    excerpt = models.CharField(max_length=128, verbose_name='摘要', blank=True)
    body = models.TextField()
    view_count = models.PositiveIntegerField(default=0, verbose_name='浏览量', help_text='浏览量')
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    def view_add(self):
        self.view_count +=1
        self.save(update_fields=['view_count'])

    def save(self, *args, **kwargs):
        if not self.excerpt:
            md = markdown.Markdown(extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
                'markdown.extensions.fenced_code',
                'markdown.extensions.sane_lists',
                'markdown.extensions.abbr',
                'markdown.extensions.attr_list',
                'markdown.extensions.def_list',
                'markdown.extensions.footnotes',
                'markdown.extensions.smart_strong',
                'markdown.extensions.meta',
                'markdown.extensions.nl2br',
                'markdown.extensions.tables',
            ])
            self.excerpt = strip_tags(md.convert(self.body))[:98]
        super(Article, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('blog:detail', kwargs={'pk': self.pk})

    class Meta:
        ordering = ['-create_time', '-update_time']
        verbose_name = verbose_name_plural = '文章'
        db_table = 'article'
